#!/bin/bash
# 从本地缓存安装 OpenCV，避免 CocoaPods 重新下载

set -e

CACHE_DIR="$HOME/Library/Caches/CocoaPods/Pods/Release"
ZIP_FILE="$CACHE_DIR/opencv-4.1.0-ios-framework.zip"
LOCAL_OPENCV_DIR="$HOME/Library/Caches/CocoaPods/Pods/Local/OpenCV"

echo "🔧 准备本地 OpenCV 安装..."
echo ""

# 检查文件
if [ ! -f "$ZIP_FILE" ]; then
    echo "❌ 未找到 OpenCV zip 文件: $ZIP_FILE"
    exit 1
fi

echo "✅ 找到 OpenCV zip 文件: $(du -h "$ZIP_FILE" | cut -f1)"
echo ""

# 创建本地目录
mkdir -p "$LOCAL_OPENCV_DIR"
cd "$LOCAL_OPENCV_DIR"

# 解压文件
if [ ! -d "opencv2.framework" ]; then
    echo "📦 解压 OpenCV..."
    unzip -q "$ZIP_FILE" || {
        echo "❌ 解压失败"
        exit 1
    }
    echo "✅ 解压完成"
else
    echo "✅ OpenCV 已解压"
fi

echo ""
echo "📋 创建本地 podspec..."
cat > OpenCV.podspec << 'PODSPEC'
Pod::Spec.new do |s|
  s.name             = 'OpenCV'
  s.version          = '4.1.0'
  s.summary          = 'OpenCV for iOS'
  s.description      = 'OpenCV framework for iOS'
  s.homepage         = 'https://opencv.org'
  s.license          = { :type => 'BSD' }
  s.author           = 'OpenCV Team'
  s.platform         = :ios, '8.0'
  s.source           = { :path => '.' }
  s.vendored_frameworks = 'opencv2.framework'
  s.frameworks = 'Accelerate', 'AssetsLibrary', 'AVFoundation', 'CoreGraphics', 'CoreImage', 'CoreMedia', 'CoreVideo', 'Foundation', 'QuartzCore', 'UIKit'
  s.libraries = 'c++'
end
PODSPEC

echo "✅ 本地 podspec 已创建"
echo ""
echo "💡 现在修改 Podfile 使用本地 OpenCV："
echo "   在 Podfile 中添加："
echo "   pod 'OpenCV', :path => '$LOCAL_OPENCV_DIR'"
echo ""
echo "   或者运行以下命令自动添加："
echo "   sed -i.bak \"s/.*pod 'OpenCV'/pod 'OpenCV', :path => '\\$HOME\/Library\/Caches\/CocoaPods\/Pods\/Local\/OpenCV'/\" Podfile"

